package com.rongshu.sendmessage.util;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.os.EnvironmentCompat;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.StreamCorruptedException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ObjectUtil {

    public static final int REQUEST_CALL_PERMISSION=102;

    /**
     * 判断是否有某项权限
     *
     * @param string_permission 权限
     * @param request_code      请求码
     * @return
     */
    public static boolean checkReadPermission(Activity activity, String string_permission, int request_code) {
        boolean flag = false;
        if (ContextCompat.checkSelfPermission(activity, string_permission) == PackageManager.PERMISSION_GRANTED) {//已有权限
            flag = true;
        } else {//申请权限
            ActivityCompat.requestPermissions(activity, new String[]{string_permission}, request_code);
        }
        return flag;
    }
    /**
       * 四舍五入保留两位
       *
       * @param money
       *
       * @return
       */
     public static String totalMoney(double money) {
        BigDecimal bigDec = new BigDecimal(money);
        double total = bigDec.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(total);
    }
    private ObjectUtil() {
        throw new AssertionError();
    }

    /**
     * compare two object
     *
     * @param actual
     * @param expected
     * @return <ul>
     *         <li>if both are null, return true</li>
     *         <li>return actual.{@link Object#equals(Object)}</li>
     *         </ul>
     */
    public static boolean isEquals(Object actual, Object expected) {
        return actual == expected || (actual == null ? expected == null : actual.equals(expected));
    }
    //获取屏幕的宽度
    public static int getScreenWidth(Context context){
        WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int widths = outMetrics.widthPixels;
        return widths;
    }
    //判断输入大于0的整数
    public  static boolean isNumericGt0(String str){
        Pattern p = Pattern
                .compile("^([0-9][0-9]*)$");
        Matcher m = p.matcher(str);
        return m.matches();
    }
    public static boolean isPositiveDecimal(String orginal){
        String regex="\\+{0,1}[0]\\.[0-9]*|\\+{0,1}[1-9]\\d*\\.\\d*";
        if (orginal == null || orginal.trim().equals("")) {
            return false;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher isNum = pattern.matcher(orginal);
        return isNum.matches();
    }
    public static boolean isBlank(String str) {
        return (str == null || str.trim().length() == 0||str.equals("null"));
    }

    public static String SceneList2String(List SceneList)
            throws IOException {
        // 实例化一个ByteArrayOutputStream对象，用来装载压缩后的字节文件。
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 然后将得到的字符数据装载到ObjectOutputStream
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                byteArrayOutputStream);
        // writeObject 方法负责写入特定类的对象的状态，以便相应的 readObject 方法可以还原它
        objectOutputStream.writeObject(SceneList);
        // 最后，用Base64.encode将字节文件转换成Base64编码保存在String中
        String SceneListString = new String(Base64.encode(
                byteArrayOutputStream.toByteArray(), Base64.DEFAULT));
        // 关闭objectOutputStream
        objectOutputStream.close();
        return SceneListString;

    }



    @SuppressWarnings("unchecked")
    public static List String2SceneList(String SceneListString)
            throws StreamCorruptedException, IOException,
            ClassNotFoundException {
        byte[] mobileBytes = Base64.decode(SceneListString.getBytes(),
                Base64.DEFAULT);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                mobileBytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(
                byteArrayInputStream);
        List SceneList = (List) objectInputStream
                .readObject();
        objectInputStream.close();
        return SceneList;
    }


    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    public static  int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = context.getPackageManager().getPackageInfo(
                    "fanggu.org.lotteryapplication", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
    /**
     * null Object to empty string
     *
     * <pre>
     * nullStrToEmpty(null) = &quot;&quot;;
     * nullStrToEmpty(&quot;&quot;) = &quot;&quot;;
     * nullStrToEmpty(&quot;aa&quot;) = &quot;aa&quot;;
     * </pre>
     *
     * @param str
     * @return
     */
    public static String nullStrToEmpty(Object str) {
        return (str == null ? "" : (str instanceof String ? (String)str : str.toString()));
    }

    /**
     * convert long array to Long array
     *
     * @param source
     * @return
     */
    public static Long[] transformLongArray(long[] source) {
        Long[] destin = new Long[source.length];
        for (int i = 0; i < source.length; i++) {
            destin[i] = source[i];
        }
        return destin;
    }
    /**
     * convert Long array to long array
     *
     * @param source
     * @return
     */
    public static long[] transformLongArray(Long[] source) {
        long[] destin = new long[source.length];
        for (int i = 0; i < source.length; i++) {
            destin[i] = source[i];
        }
        return destin;
    }

    /**
     * convert int array to Integer array
     *
     * @param source
     * @return
     */
    public static Integer[] transformIntArray(int[] source) {
        Integer[] destin = new Integer[source.length];
        for (int i = 0; i < source.length; i++) {
            destin[i] = source[i];
        }
        return destin;
    }

    /**
     * convert Integer array to int array
     *
     * @param source
     * @return
     */
    public static int[] transformIntArray(Integer[] source) {
        int[] destin = new int[source.length];
        for (int i = 0; i < source.length; i++) {
            destin[i] = source[i];
        }
        return destin;
    }

    /**
     * compare two object
     * <ul>
     * <strong>About result</strong>
     * <li>if v1 > v2, return 1</li>
     * <li>if v1 = v2, return 0</li>
     * <li>if v1 < v2, return -1</li>
     * </ul>
     * <ul>
     * <strong>About rule</strong>
     * <li>if v1 is null, v2 is null, then return 0</li>
     * <li>if v1 is null, v2 is not null, then return -1</li>
     * <li>if v1 is not null, v2 is null, then return 1</li>
     * <li>return v1.{@link Comparable#compareTo(Object)}</li>
     * </ul>
     *
     * @param v1
     * @param v2
     * @return
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static <V> int compare(V v1, V v2) {
        return v1 == null ? (v2 == null ? 0 : -1) : (v2 == null ? 1 : ((Comparable)v1).compareTo(v2));
    }

    public static String toString(Object obj, String def){
        return obj == null || "".equals(String.valueOf(obj))  ?def : String.valueOf(obj);
    }
    public static String toString(Object obj){
        return obj == null ?"" : String.valueOf(obj);
    }

    public static Double toDouble(Object obj){
        BigDecimal big = toBigDecimal(obj);
        return  big == null ? 0:big.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static Float toFloat(Object obj){
        BigDecimal big = toBigDecimal(obj);
        return  big == null ? 0:big.setScale(1).floatValue();
    }

    public static Integer toInteger(Object obj){
        try{
            BigDecimal big = toBigDecimal(obj);
            return  big == null ? 0:big.intValue();
        }catch (Exception e){
            return 0;
        }
    }

    public static BigDecimal toBigDecimal(Object obj){
        try {
            return new BigDecimal(String.valueOf(obj));
        }catch (Exception e){
            return  null;
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    /**
     * 获取当前年月日，和上一天，和上上一天的日期，返回数组
     */
    public static String[] getTime() {
        long dayTimes = System.currentTimeMillis();
        long up_dayTimes = System.currentTimeMillis()-24*1000*60*60;
        long up_up_dayTimes = System.currentTimeMillis()-24*1000*60*60*2;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String[] times ={sdf.format(new Date(dayTimes)),sdf.format(new Date(up_dayTimes)),sdf.format(new Date(up_up_dayTimes))};

        return times;
    }

    public static String formatMoney(BigDecimal m){
        DecimalFormat df = new DecimalFormat("#0.00");//保留两位小数
        return  df.format(m);
    }

    public static int parseColor(String c){
        try{
            return  Color.parseColor("#" +c.replace("#",""));
        }catch (Exception e){
            return  Color.parseColor("#595959");
        }

    }

    public static String formet2(float aq) {
        String s = String.format("%.2f", aq);
        return s;
    }

    public static Date parseData(String birthDayStr) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date d;
        try {
            d=sdf.parse(birthDayStr);
        } catch (ParseException e) {
            d=new Date();
            e.printStackTrace();
        }
        return d;
    }
    public static String dateParseString(Date date) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String d;
        try {
            d=sdf.format(date);
        } catch (Exception e) {
            d="2019-12-12";
            e.printStackTrace();
        }
        return d;
    }

    public static String getErrorStr(Exception e) {
        StringWriter sw = null;
        PrintWriter pw;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            String ss="\r\n" + sw.toString() + "\r\n";
            sw.close();
            pw.close();
            return ss;
        } catch (Exception e2) {
          e2.printStackTrace();
        }
        return "无法解析的错误！！！";
    }
    public static Uri createImageUri(Context mContext) {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return ((Activity) mContext).getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return ((Activity) mContext).getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }
    public static File getNewFile(Context mContext, String fileName) {
        SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sFormat.format(new Date());
        File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File tempFile = new File(storageDir, format+fileName);
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }
        return tempFile;
    }
    public static Bitmap getYaSuo(Bitmap bit){
        Matrix matrix = new Matrix();
        matrix.setScale(0.5f, 0.5f);
        Bitmap bm = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(), bit.getHeight(), matrix, true);
        return bm;
    }
    public static Uri getImageContentUri(Context context, String path) {
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ",
                new String[] { path }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            // 如果图片不在手机的共享图片数据库，就先把它插入。
            if (new File(path).exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, path);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }
    public static Bitmap getBitmapFromUri(Context context, Uri uri) {
        try {
            ParcelFileDescriptor parcelFileDescriptor =
                    context.getContentResolver().openFileDescriptor(uri, "r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            parcelFileDescriptor.close();
            return image;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDateTime(String createTime) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long time = sdf.parse(createTime).getTime();
            long l = System.currentTimeMillis();
            long xiaoshi=(l-time)/1000/60/60;
            if(xiaoshi==0){//不到1小时
                return  "刚刚";
            }else if(xiaoshi>0&&xiaoshi<24){//就是几小时
                return xiaoshi+"小时前";
            }else{
                long tian = xiaoshi / 24;
                if(tian<30){//几天
                    return tian+"天前";
                }else{
                    long yue = tian / 30;
                    if(yue<12){//就是月
                        return  yue+"月前";
                    }else{
                        return yue/12+"天前";
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "未获取到时间";
    }

}
